//
//  DZMReadOperation.swift
//  DZMeBookRead
//
//  Created by 邓泽淼 on 2017/5/15.
//  Copyright © 2017年 DZM. All rights reserved.
//

import UIKit

class DZMReadOperation: NSObject {

    /// 阅读控制器
    weak var vc:CLReadViewController!
    
    // MARK: -- init
    
    init(vc:CLReadViewController) {
        super.init()
        self.vc = vc
    }
    
    //获取当前页面的最顶层控制器
    func currentVc() -> UIViewController {

        let keywindow = UIApplication.shared.keyWindow
        let firstView: UIView = keywindow?.subviews.first as! UIView
        if firstView != nil {
            let secondView: UIView = firstView.subviews.first as! UIView
            let vc = viewForController(view: secondView)
            return vc!
        }else {
            //let vc = viewForController(view: firstView);
            //return vc!
            let vc = keywindow?.rootViewController;
            return vc!;
        }

    }
    
    func viewForController(view:UIView) -> UIViewController? {
        var next:UIView? = view
        repeat {
            if let nextResponder = next?.next, nextResponder is UIViewController {
                return (nextResponder as? UIViewController)
            }
            next = next?.superview
        } while next != nil
        return nil
    }
    
    // MARK: -- 更新阅读记录
    func update(record:CLBookRecord?, isSave:Bool = true) {
        guard let record_ = record else { return }
        //判断是否切换了章节
        
        // 修改阅读记录
        self.vc.record = record_
        
        if isSave {
            // 上传阅读记录
            
            // 保存阅读记录到本地
            
            // 更新UI
            DispatchQueue.main.async { [weak self] ()->Void in
                // 进度条数据初始化
                self?.vc.readMenu.bottomView.sliderUpdate()
            }
        }
    }
    
}

extension DZMReadOperation {
    
    /// 检查章节， 是否可以阅读，是否已经加载内容，是否需要购买
    func checkChapter(chapterId:Int, complete:(()->Void)?) {
        let chapters = self.vc.book.chapters
        
        if let chapter = chapters.chapter(id: chapterId) {
            
            if chapter.code == "2" {
                // 需要购买
                print("需要购买")
            } else {
                // 先判断章节内容是否已经加载
                if chapter.content.isEmpty {
                    // 网络加载章节内容
                    if let index = chapters.firstIndex(where: { (item) -> Bool in
                        return item.id == chapterId
                    }) {
                        self.loadChapterContent(index: index) {
                            complete?()
                        }
                    } else {
                        // 章节不存在
                        print("章节不存在")
                    }
                } else {
                    // 可以查看了
                    complete?()
                }
                
            }
            
        } else {
            // 章节不存在
            print("章节不存在")
        }
        
    }

    /// 跳转指定章节的page
    func goto(chapter:CLBookChapter?, page:Int) {
        //修改阅读记录
        let record = CLBookRecord(page: page, chapter: chapter)
        self.vc.record = record
        //刷新阅读器
        let pageController = self.getCurrent(isUpdateFont: true, isSave: true)
        self.vc.reloadController(display: pageController)
    }
    
}

// MARK: -- 获取阅读控制器 DZMReadViewController
extension DZMReadOperation {
    
    /// 获取阅读View控制器
    private func getControllerBy(record:CLBookRecord?) -> DZMReadViewController? {
        if let record_ = record {
            let controller = DZMReadViewController()
            controller.chapterPage = record_
            controller.readController = vc
            return controller
        } else {
            return nil
        }
    }
    
    /// 获取当前阅读记录的阅读View控制器
    func getCurrent(isUpdateFont:Bool = false, isSave:Bool = false) -> DZMReadViewController? {
        if isUpdateFont { self.vc.record?.chapter?.reload() }
        if isSave { self.update(record: self.vc.record) }
        let record = self.vc.record?.copy
        return self.getControllerBy(record: record)
    }
    
    /// 获取上一页控制器
    func getAbove() -> DZMReadViewController? {
        
        // 获得阅读记录
        guard let record = vc.record?.copy, let chapter = record.chapter else { return nil }
        
        let chapters = vc.book.chapters
        
        // 判断是否书本开始
        if chapters.first?.id == chapter.id && record.page == 0 { return nil }
        
        if record.page == 0 {
            // 这一章到头了, 选取前一章的最后一页
            if let index = chapters.firstIndex(where: { (item) -> Bool in
                return item.id == chapter.id
            }) {
                let preChapter = chapters[index - 1]
                if !preChapter.content.isEmpty {
                    record.chapter = preChapter
                    record.page = preChapter.pages - 1
                } else {
                    self.loadChapterContent(index: index - 1, completeHandle: nil)
                }
            } else {
                print("未找到章节")
                return nil
            }
        } else {
            // 没到头
            record.page -= 1
        }
        
        return self.getControllerBy(record: record)
    }
    
    /// 获得下一页控制器
    func getBelow() -> DZMReadViewController? {
        
        // 获得阅读记录
        guard let record = vc.record?.copy, let chapter = record.chapter else { return nil }
        
        let chapters = vc.book.chapters
        let lastPage = chapter.pages - 1
        
        // 判断是否书本最后一页
        if chapters.last?.id == chapter.id && record.page == lastPage {
            self.vc.hud.showText("已经是最后一页")
            return nil
        }
        
        if record.page == lastPage {
            
            // 这一章结束了,切换下一章
            if let index = chapters.firstIndex(where: { (item) -> Bool in
                return item.id == chapter.id
            }) {
                let nextChapter = chapters[index + 1]
                
                if !nextChapter.content.isEmpty {
                    record.page = 0
                    record.chapter = nextChapter
                } else {
                    self.loadChapterContent(index: index + 1, completeHandle: nil)
                }
            } else {
                print("未找到章节")
                return nil
            }
            
        } else {
            // 没读完，下一页
            record.page += 1
        }
        
        return self.getControllerBy(record: record)
    }
    
}

//MARK: - 加载网络加载章节内容
extension DZMReadOperation {
    
    /// 加载章节内容
    func loadChapterContent(index:Int,completeHandle:(()->Void)?) {
        
        self.vc.hud.showProgress()
        
        //加载当前章节
        let currentChapter = vc.book.chapters[index]
        let token = AccountManager.shared.token
        
        // 网络加载章节内容
        _ = Router.fetchChapterContent(goods_id: currentChapter.goods_id, id: currentChapter.id, token: token).request { [weak self] (response:RequestResponse<String>) in
            
            self?.vc.hud.hide()
            
            if case .success(let res,_) = response {
                if let content = res {
                    currentChapter.setContent(html: content)
                    currentChapter.setEpubContents()
                    currentChapter.reload()
                    completeHandle?()
                }
            }
            
            if case .failure(_,let message) = response {
                self?.vc.hud.showText(message)
            }
        }
        
        //加载上一章节
        if index > 0 {
            let preIndex = index - 1
            let preChapter = vc.book.chapters[preIndex]
            
            if preChapter.content.isEmpty {
                _ = Router.fetchChapterContent(goods_id: preChapter.goods_id, id: preChapter.id, token: token).request { (response:RequestResponse<String>) in
                    if case .success(let res,_) = response {
                        if let content = res {
                            preChapter.setContent(html: content)
                            preChapter.setEpubContents()
                            preChapter.reload()
                            print(content)
                        }
                    }
                }
            }
        }
        
        //加载下一章节
        if index < vc.book.chapters.count - 1 {
            let nextIndex = index + 1
            let nextChapter = vc.book.chapters[nextIndex]
            
            if nextChapter.content.isEmpty {
                _ = Router.fetchChapterContent(goods_id: nextChapter.goods_id, id: nextChapter.id, token: token).request { (response:RequestResponse<String>) in
                    if case .success(let res,_) = response {
                        if let content = res {
                            nextChapter.setContent(html: content)
                            nextChapter.setEpubContents()
                            nextChapter.reload()
                            print(content)
                        }
                    }
                }
            }
        }

    }
}
